<template>
	<view class="content-box">
		<!-- 头部navbar -->
		<navbar :fixed="true" :bgColor="'#fff'" :title="t('my.lszd')" :leftIcon="true"></navbar>

		<!-- 无数据状态 -->
		<view class="no-data" v-if="!hasData">
			<image class="no-data-img" src="/static/image/my/bg7.svg" mode="aspectFit"></image>
			<text class="no-data-text">{{t('billing.zsmy')}}</text>
			<view class="refresh-btn" @click="refreshData">
				<text>{{t('billing.sxsj')}}</text>
			</view>
		</view>

		<!-- 有数据状态 -->
		<view class="has-data" v-else>
			<!-- 标签切换 -->
			<view class="tab-container">
				<view class="tab-item" :class="{active: activeTab === 'all'}" @click="switchTab('all')">
					{{t('billing.zp')}}
				</view>
				<view class="tab-item" :class="{active: activeTab === 'recharge'}" @click="switchTab('recharge')">
					{{t('my.cz')}}
				</view>
				<view class="tab-item" :class="{active: activeTab === 'withdraw'}" @click="switchTab('withdraw')">
					{{t('my.tx')}}
				</view>
			</view>

			<!-- 时间筛选 -->
			<view class="time-filter">
				<view class="filter-item" :class="{active: activeFilter === '3days'}" @click="switchFilter('3days')">
					{{t('billing.j3t')}}
				</view>
				<view class="filter-item" :class="{active: activeFilter === '7days'}" @click="switchFilter('7days')">
					{{t('billing.j7t')}}
				</view>
				<view class="filter-item" :class="{active: activeFilter === '1month'}" @click="switchFilter('1month')">
					{{t('billing.j1y')}}
				</view>
				<view class="filter-item" :class="{active: activeFilter === '1year'}" @click="switchFilter('1year')">
					{{t('billing.j1n')}}
				</view>
				<view class="filter-item" :class="{active: activeFilter === 'all'}" @click="switchFilter('all')">
					{{t('billing.qb')}}
				</view>
			</view>

			<!-- 加载状态 -->
			<view class="loading-container" v-if="loading">
				<view class="loading-spinner"></view>
				<text class="loading-text">{{t('billing.loading')}}</text>
			</view>

			<!-- 账单列表 -->
			<view class="bill-list" v-else-if="activeTab === 'all'">
				<!-- 质押账单 -->
				<view class="bill-item" v-for="(item, index) in billList" :key="item.id" @click="viewDetails(item.id)">
					<view class="bill-header">
						<view class="left">
							<view class="bill-title">{{item.title}}</view>
							<view class="bill-status" :class="item.status === 'ongoing' ? 'status-ongoing' : 'status-completed'">
								{{item.status === 'ongoing' ? t('billing.jxz') : t('billing.yjs')}}
							</view>
						</view>
						<view class="right">
							<text>详情</text>
							<image src="/static/image/my/detail.svg" mode=""></image>
						</view>
					</view>
					<view class="bill-content">
						<view class="content-row">
							<view class="content-label">{{t('billing.gmje')}}</view>
							<view class="content-label">{{t('billing.zq')}}</view>
							<view class="content-label">{{t('billing.ll')}}</view>
							<view class="content-label">{{t('billing.zsy')}}</view>
						</view>
						<view class="content-row values">
							<view class="content-value">{{item.amount}}</view>
							<view class="content-value">{{item.period}}</view>
							<view class="content-value rate">{{item.rate}}</view>
							<view class="content-value profit">{{item.profit}}</view>
						</view>
					</view>
					<!-- <view class="bill-action">
						<view class="action-details">
							{{t('billing.xq')}} ≡
						</view>
					</view> -->
				</view>
			</view>
			<!-- 充值和提现账单 -->
			<view class="bill-list" v-else>
				<view class="withdrawal-bill-item" v-for="(item, index) in (activeTab === 'recharge' ? rechargeList : withdrawalList)" :key="index"
					@click="viewDetails(item.id)">
					<view class="top-box">
						<view class="left">
							订单号：{{item.orderNum}}
							<image src="/static/icon/copy-icon.svg" mode=""></image>
						</view>
						<view class="right">
							<view class="top-up-box" v-if="activeTab === 'recharge'">
								<view class="status-tag">{{item.status}}</view>
							</view>
							<view class="withdrawal-box" v-if="activeTab === 'withdraw'">
								<view class="status-tag">{{item.status}}</view>
							</view>
						</view>
					</view>
					<view class="bottom-box">
						<view class="left">
							{{t('billing.ccje')}}：{{item.amount}}
						</view>
						<view class="right">
							{{t('billing.sj')}}：{{item.createTime}}
						</view>
					</view>
				</view>
				<!-- 空列表提示 -->
				<view class="empty-list" v-if="billList.length === 0">
					<image src="/static/icon/bill-bg.svg" mode=""></image>
					<!-- <view class="title">{{t('billing.wgd')}}</view> -->
					<view class="title">{{t('billing.zsmy')}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		useI18n
	} from 'vue-i18n';
	import {
		ref,
		onMounted
	} from 'vue';
	import { pledgeApi, rechargeApi, withdrawApi } from '@/utils/api.js';
	const {
		t,
		locale
	} = useI18n();

	// 是否有数据，用于切换显示状态
	const hasData = ref(true); // 默认为true，可以通过切换查看两种状态

	// 是否正在加载数据
	const loading = ref(false);

	// 当前激活的标签
	const activeTab = ref('all');

	// 当前激活的时间筛选
	const activeFilter = ref('all'); // 默认选中全部标签

	// 分页相关状态
	const pageNo = ref(1);
	const pageSize = ref(10);
	const total = ref(0);
	const hasMore = ref(true);

	// 账单数据
	const billList = ref([]);
	
	// 充值订单数据
	const rechargeList = ref([]);
	
	// 提现订单数据（暂时为空）
	const withdrawalList = ref([]);

	// 生成时间筛选参数
	const getTimeFilterParams = () => {
		if (activeFilter.value === 'all') {
			return {}; // 全部标签不添加createTime参数
		}

		const now = new Date();
		const endTime = now;
		let startTime = new Date();

		// 根据筛选条件计算开始时间
		switch (activeFilter.value) {
			case '3days':
				startTime.setDate(now.getDate() - 3);
				break;
			case '7days':
				startTime.setDate(now.getDate() - 7);
				break;
			case '1month':
				startTime.setMonth(now.getMonth() - 1);
				break;
			case '1year':
				startTime.setFullYear(now.getFullYear() - 1);
				break;
			default:
				return {};
		}

		// 格式化时间为 YYYY-MM-DD HH:mm:ss 格式
		const formatTime = (date) => {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		};

		const startTimeStr = formatTime(startTime);
		const endTimeStr = formatTime(endTime);

		return {
			createTime: `${startTimeStr},${endTimeStr}`
		};
	};

	// 切换标签
	const switchTab = (tab) => {
		activeTab.value = tab;
		// 重置分页
		pageNo.value = 1;
		// 清空所有数据
		billList.value = [];
		rechargeList.value = [];
		withdrawalList.value = [];
		// 重新获取数据
		fetchBillData();
	};

	// 切换时间筛选
	const switchFilter = (filter) => {
		activeFilter.value = filter;
		// 重置分页
		pageNo.value = 1;
		// 清空所有数据
		billList.value = [];
		rechargeList.value = [];
		withdrawalList.value = [];
		// 重新获取数据
		fetchBillData();
	};

	// 查看详情
	const viewDetails = (id) => {
		uni.navigateTo({ url: `/pages/my/orderDetails?id=${id}` });
	};

	// 获取质押订单数据
	// 格式化时间戳为日期字符串
	const formatTimestamp = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		return date.toLocaleDateString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit'
		});
	};

	// 转换API数据格式为页面需要的格式
	const transformApiData = (apiData) => {
		return apiData.map(item => ({
			id: item.id,
			title: item.productName, // API的productName -> 页面的title
			status: item.status === 1 ? 'ongoing' : 'completed', // 1=进行中, 2=已完成
			amount: `¥${item.amount.toFixed(2)}`, // 格式化金额
			period: `${item.cycle}天`, // API的cycle -> 页面的period
			rate: `${item.rate}%`, // 格式化利率
			profit: `¥${item.totalProfit.toFixed(2)}`, // API的totalProfit -> 页面的profit
			startTime: formatTimestamp(item.startTime),
			endTime: formatTimestamp(item.endTime),
			createTime: formatTimestamp(item.createTime),
			orderId: item.orderId,
			statusLabel: item.statusLabel,
			currentCycle: item.currentCycle,
			nextSettleTime: formatTimestamp(item.nextSettleTime)
		}));
	};

	// 转换充值订单API数据格式为页面需要的格式
	const transformRechargeData = (apiData) => {
		return apiData.map(item => ({
			id: item.id,
			orderNum: item.paySn, // API的paySn -> 页面的orderNum
			amount: `¥${item.payAmount.toFixed(2)}`, // 格式化充值金额
			status: item.statusLabel, // 直接使用statusLabel
			createTime: formatTimestamp(item.createTime),
			payTime: formatTimestamp(item.payTime),
			payTypeLabel: item.payTypeLabel,
			userName: item.userName,
			firstRecharge: item.firstRecharge
		}));
	};

	// 转换提现订单API数据格式为页面需要的格式
	const transformWithdrawData = (apiData) => {
		return apiData.map(item => ({
			id: item.id,
			orderNum: item.orderId, // API的orderId -> 页面的orderNum
			amount: `¥${item.withAmount.toFixed(2)}`, // 格式化提现金额
			status: item.statusLabel, // 直接使用statusLabel
			createTime: formatTimestamp(item.createTime),
			auditTime: formatTimestamp(item.auditTime),
			withAddress: item.withAddress,
			withFee: item.withFee,
			realAmount: item.realAmount,
			auditDescription: item.auditDescription,
			userName: item.userName,
			firstWithdraw: item.firstWithdraw,
			withdrawType: item.withdrawType
		}));
	};

	const fetchBillData = async () => {
		try {
			loading.value = true;

			// 根据当前标签决定调用哪个API
			if (activeTab.value === 'all') {
				// 质押订单
				await fetchPledgeData();
			} else if (activeTab.value === 'recharge') {
				// 充值订单
				await fetchRechargeData();
			} else if (activeTab.value === 'withdraw') {
				// 提现订单
				await fetchWithdrawData();
			}
		} catch (error) {
			// 请求异常
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
			
			// 如果是第一页且请求失败，显示无数据状态
			if (pageNo.value === 1) {
				hasData.value = false;
				billList.value = [];
				rechargeList.value = [];
			}
		} finally {
			loading.value = false;
		}
	};

	// 获取质押订单数据
	const fetchPledgeData = async () => {
		// 构建请求参数
		const params = {
			pageNo: pageNo.value,
			pageSize: pageSize.value,
			...getTimeFilterParams() // 根据时间筛选添加createTime参数
		};

		// 调用质押订单分页API
		const response = await pledgeApi.getOrderPage(params);

		if (response && response.code === 0) {
			const { data } = response;
			
			// 更新总数和是否还有更多数据
			total.value = data.total || 0;
			hasMore.value = (pageNo.value * pageSize.value) < total.value;
			
			// 转换API数据格式
			const transformedData = transformApiData(data.list || []);
			
			// 如果是第一页，直接赋值；否则追加数据
			if (pageNo.value === 1) {
				billList.value = transformedData;
			} else {
				// 追加数据时进行去重，避免重复数据
				const existingIds = new Set(billList.value.map(item => item.id));
				const newData = transformedData.filter(item => !existingIds.has(item.id));
				billList.value = [...billList.value, ...newData];
			}

			// 更新是否有数据的状态
			hasData.value = billList.value.length > 0;
		} else {
			// API返回错误
			uni.showToast({
				title: response?.msg || '获取数据失败',
				icon: 'none'
			});
			
			// 如果是第一页且没有数据，显示无数据状态
			if (pageNo.value === 1) {
				hasData.value = false;
				billList.value = [];
			}
		}
	};

	// 获取充值订单数据
	const fetchRechargeData = async () => {
		// 构建请求参数
		const params = {
			pageNo: pageNo.value,
			pageSize: pageSize.value,
			...getTimeFilterParams() // 根据时间筛选添加createTime参数
		};

		// 调用充值订单分页API
		const response = await rechargeApi.getOrderPage(params);

		if (response && response.code === 0) {
			const { data } = response;
			
			// 更新总数和是否还有更多数据
			total.value = data.total || 0;
			hasMore.value = (pageNo.value * pageSize.value) < total.value;
			
			// 转换API数据格式
			const transformedData = transformRechargeData(data.list || []);
			
			// 如果是第一页，直接赋值；否则追加数据
			if (pageNo.value === 1) {
				rechargeList.value = transformedData;
			} else {
				// 追加数据时进行去重，避免重复数据
				const existingIds = new Set(rechargeList.value.map(item => item.id));
				const newData = transformedData.filter(item => !existingIds.has(item.id));
				rechargeList.value = [...rechargeList.value, ...newData];
			}

			// 更新是否有数据的状态
			hasData.value = rechargeList.value.length > 0;
		} else {
			// API返回错误
			uni.showToast({
				title: response?.msg || '获取数据失败',
				icon: 'none'
			});
			
			// 如果是第一页且没有数据，显示无数据状态
			if (pageNo.value === 1) {
				hasData.value = false;
				rechargeList.value = [];
			}
		}
	};

	// 获取提现订单数据
	const fetchWithdrawData = async () => {
		// 构建请求参数
		const params = {
			pageNo: pageNo.value,
			pageSize: pageSize.value,
			...getTimeFilterParams() // 根据时间筛选添加createTime参数
		};

		// 调用提现订单分页API
		const response = await withdrawApi.getOrderPage(params);

		if (response && response.code === 0) {
			const { data } = response;
			
			// 更新总数和是否还有更多数据
			total.value = data.total || 0;
			hasMore.value = (pageNo.value * pageSize.value) < total.value;
			
			// 转换API数据格式
			const transformedData = transformWithdrawData(data.list || []);
			
			// 如果是第一页，直接赋值；否则追加数据
			if (pageNo.value === 1) {
				withdrawalList.value = transformedData;
			} else {
				// 追加数据时进行去重，避免重复数据
				const existingIds = new Set(withdrawalList.value.map(item => item.id));
				const newData = transformedData.filter(item => !existingIds.has(item.id));
				withdrawalList.value = [...withdrawalList.value, ...newData];
			}

			// 更新是否有数据的状态
			hasData.value = withdrawalList.value.length > 0;
		} else {
			// API返回错误
			uni.showToast({
				title: response?.msg || '获取数据失败',
				icon: 'none'
			});
			
			// 如果是第一页且没有数据，显示无数据状态
			if (pageNo.value === 1) {
				hasData.value = false;
				withdrawalList.value = [];
			}
		}
	};

	// 加载更多数据
	const loadMore = () => {
		if (!loading.value && hasMore.value) {
			pageNo.value += 1;
			fetchBillData();
		}
	};

	// 刷新数据
	const refreshData = () => {
		// 重置分页状态
		pageNo.value = 1;
		hasMore.value = true;
		// 清空所有数据
		billList.value = [];
		rechargeList.value = [];
		withdrawalList.value = [];
		hasData.value = true;
		// 重新获取数据
		fetchBillData();
	};

	// 页面加载时获取数据
	onMounted(() => {
		fetchBillData();
	});
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding: 20rpx 30rpx 100rpx;
		padding: 41.86rpx 34.89rpx;
		box-sizing: border-box;
	}

	/* 无数据状态 */
	.no-data {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-top: 200rpx;

		.no-data-img {
			width: 409.91rpx;
			height: 318.85rpx;
		}

		.no-data-text {
			font-size: 31.4rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 45.46rpx;
			color: rgba(61, 62, 82, 1);
			margin-top: 30rpx;
			margin-bottom: 40rpx;
		}

		.refresh-btn {
			background-color: #2979FF;
			color: #fff;
			padding: 15rpx 40rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			box-shadow: 0 4rpx 10rpx rgba(41, 121, 255, 0.3);
			transition: all 0.3s ease;

			&:active {
				transform: scale(0.95);
			}
		}
	}

	/* 有数据状态 */
	.has-data {

		/* 标签切换 */
		.tab-container {
			display: flex;
			justify-content: space-between;
			// background-color: #fff;
			margin-bottom: 31.4rpx;

			.tab-item {
				flex: 1;
				text-align: center;
				font-size: 31.4rpx;
				color: rgba(51, 51, 51, 1);
				position: relative;

				&.active {
					font-weight: 500;

					&::after {
						content: '';
						position: absolute;
						bottom: -10rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 34.89rpx;
						height: 6.98rpx;
						background: rgba(2, 123, 217, 1);
						border-radius: 3rpx;
					}
				}
			}
		}

		/* 时间筛选 */
		.time-filter {
			display: flex;
			justify-content: space-between;
			overflow-x: auto;
			white-space: nowrap;
			margin: 0 50.58rpx;
			margin-bottom: 55.82rpx;
			padding-bottom: 6.98rpx;
			border-bottom: 1.74rpx solid rgba(230, 230, 230, 1);

			.filter-item {
				font-size: 31.4rpx;
				font-weight: 400;
				color: rgba(102, 102, 102, 1);

				&.active {
					font-size: 31.4rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 45.46rpx;
					color: rgba(2, 123, 217, 1);
				}
			}
		}

		/* 加载状态 */
		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60rpx 0;

			.loading-spinner {
				width: 60rpx;
				height: 60rpx;
				border: 4rpx solid rgba(41, 121, 255, 0.2);
				border-top-color: #2979FF;
				border-radius: 50%;
				animation: spin 1s infinite linear;
			}

			.loading-text {
				margin-top: 20rpx;
				font-size: 26rpx;
				color: #999;
			}
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}

		/* 账单列表 */
		.bill-list {

			.bill-item {
				border-radius: 20.93rpx;
				background: rgba(255, 255, 255, 1);
				padding: 34.89rpx;
				margin-bottom: 20.93rpx;
				// box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
				transition: all 0.2s ease;
				position: relative;

				&:active {
					transform: scale(0.98);
					background-color: #f9f9f9;
				}

				.bill-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20.93rpx;

					.left {
						display: flex;
						align-items: center;

						.bill-title {
							font-size: 27.91rpx;
							font-weight: 500;
							letter-spacing: 0rpx;
							line-height: 40.42rpx;
							color: rgba(51, 51, 51, 1);
							margin-right: 13.95rpx;
						}

						.bill-status {
							width: 101.17rpx;
							height: 33.14rpx;
							font-size: 20.93rpx;
							font-weight: 400;
							line-height: 33.14rpx;
							color: rgba(255, 255, 255, 1);
							border-radius: 10.47rpx;
							text-align: center;

							&.status-ongoing {
								background: rgba(13, 179, 100, 1);
							}

							&.status-completed {
								background: rgba(247, 56, 79, 1);
							}
						}
					}

					.right {
						display: flex;
						align-items: center;

						text {
							font-size: 24.42rpx;
							font-weight: 400;
							letter-spacing: 0rpx;
							line-height: 35.36rpx;
							color: rgba(0, 0, 0, 1);
							margin-right: 9.59rpx;
						}

						image {
							width: 22.68rpx;
							height: 20.93rpx;
						}
					}

				}

				.bill-content {
					margin-bottom: 10rpx;

					.content-row {
						display: flex;
						justify-content: space-between;
						margin-bottom: 8rpx;
						text-align: center;

						.content-label {
							font-size: 27.91rpx;
							font-weight: 300;
							letter-spacing: 0rpx;
							line-height: 40.42rpx;
							color: rgba(0, 0, 0, 1);
							flex: 1;

							&:first-child {
								// text-align: left;
							}

							&:last-child {
								// text-align: right;
							}
						}

						.content-value {
							font-size: 24.42rpx;
							font-weight: 500;
							letter-spacing: 0rpx;
							line-height: 35.36rpx;
							color: rgba(51, 51, 51, 1);
							flex: 1;

							&:first-child {
								// text-align: left;
							}

							&:last-child {
								// text-align: right;
							}

							&.rate,
							&.profit {
								color: #18B566;
							}

							&.rate {
								color: #18B566;
							}

							&.profit {
								color: #18B566;
							}
						}
					}
				}

				.bill-action {
					display: flex;
					justify-content: flex-end;

					.action-details {
						font-size: 24rpx;
						color: #2979FF;
						display: flex;
						align-items: center;
						position: absolute;
						right: 30rpx;
						top: 20rpx;
					}
				}
			}

			.withdrawal-bill-item {
				border-radius: 20.93rpx;
				background: rgba(255, 255, 255, 1);
				padding: 34.89rpx;
				margin-bottom: 20.93rpx;
				// box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
				transition: all 0.2s ease;

				.top-box {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 20.93rpx;

					.left {
						display: flex;
						align-items: center;
						font-size: 27.91rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 40.42rpx;
						color: rgba(51, 51, 51, 1);

						image {
							margin-left: 10rpx;
							width: 22.09rpx;
							height: 22.09rpx;
						}
					}

					.right {
						view {
							min-width: 101.17rpx;
							padding: 0 11.56rpx;
							height: 33.14rpx;
							box-sizing: border-box;
							line-height: 33.14rpx;
							border-radius: 10.47rpx;
							font-size: 20.93rpx;
							color: rgba(255, 255, 255, 1);
							text-align: center;
						}

						.status-tag {
							background: rgba(13, 179, 100, 1);
						}

						.pend-tag {
							background: rgba(255, 87, 51, 1);
						}

						.end-tag {
							background: rgba(42, 130, 228, 1);
						}
					}
				}

				.bottom-box {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.left {
						font-size: 27.91rpx;
						font-weight: 300;
						letter-spacing: 0rpx;
						line-height: 40.42rpx;
						color: rgba(0, 0, 0, 1);
					}

					.right {
						font-size: 24.42rpx;
						font-weight: 300;
						letter-spacing: 0rpx;
						line-height: 35.36rpx;
						color: rgba(0, 0, 0, 1);




					}
				}
			}

			/* 空列表提示 */
			.empty-list {
				display: flex;
				justify-content: center;
				flex-direction: column;
				align-items: center;
				padding: 100rpx 0;

				image {
					width: 409.91rpx;
					height: 319.51rpx;
				}

				.title {
					font-size: 31.4rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 45.46rpx;
					color: rgba(61, 62, 82, 1);
					margin-top: 34.89rpx;
				}
			}
		}
	}
</style>